<template>
  <div class="login-background">
    <div class="login-container">
      <el-card class="login-card">
        <h2 class="login-title">用户登录</h2>
        <el-form @submit.prevent="handleLogin" class="login-form">
          <el-form-item label="用户名" :rules="rules.username">
            <el-input v-model="username" placeholder="请输入用户名">
              <template #prefix>
                <i class="el-icon-user"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" :rules="rules.password">
            <el-input v-model="password" type="password" placeholder="请输入密码">
              <template #prefix>
                <i class="el-icon-lock"></i>
              </template>
            </el-input>
          </el-form-item>
          <div class="button-container">
            <el-button type="primary" class="login-button" :loading="loading" native-type="submit">登录</el-button>
            <el-button class="register-button" @click="goToRegister">去注册</el-button>
          </div>
        </el-form>
        <div v-if="loading">正在登录，请稍候...</div>
        <div v-if="error.global" class="error-message">{{ error.global }}</div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

export default {
  name: 'UserLogin',
  setup() {
    const username = ref(null);
    const password = ref(null);
    const loading = ref(false);
    const error = ref({});
    const router = useRouter();

    const rules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    };

    const validateForm = () => {
      const newErrors = {};
      if (!username.value) newErrors.username = '请输入用户名';
      if (!password.value) newErrors.password = '请输入密码';
      return newErrors;
    };

    const setLoading = (state) => {
      loading.value = state;
    };

    const loginUser = async (username, password) => {
      const baseURL = 'http://localhost:5077';
      // Send parameters as URL-encoded query parameters
      const params = new URLSearchParams();
      params.append('username', username);
      params.append('password', password);

      return await axios.post(`${baseURL}/user/login`, params);
    };

    const handleLogin = async () => {
      setLoading(true);
      error.value = {};

      const formErrors = validateForm();
      if (Object.keys(formErrors).length) {
        error.value = formErrors;
        setLoading(false);
        return;
      }
      
      try {
        console.log('Attempting to log in with:', { username: username.value, password: password.value });
        const response = await loginUser(username.value.trim(), password.value.trim());
        const { code, data: { user_id, token, message } } = response.data;

        if (code === 100) {
          localStorage.setItem('user_id', user_id);
          localStorage.setItem('token', token);
         router.push('/home');
          console.log('登录成功的响应数据:', response.data);
        } else {
          error.value.global = message;
        }
      } catch (err) {
        console.error('Login error:', err.message);
        error.value.global = '登录失败: ' + (err.response?.data?.message || '服务器错误，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    const goToRegister = () => {
      router.push({ name: 'register' });
    };

    return {
      username,
      password,
      loading,
      error,
      handleLogin,
      goToRegister,
      rules
    };
  }
};
</script>



<style scoped>
.login-background {
  background: linear-gradient(to right, #4facfe, #89d2d6);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  animation: gradient-animation 15s ease infinite;
}

@keyframes gradient-animation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  position: relative;
}

.login-card {
  width: 400px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.35);
  z-index: 1;
  transition: transform 0.3s, opacity 0.3s;
  opacity: 0.95;
}

.login-card:hover {
  transform: scale(1.02);
  opacity: 1;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 15px; /* Adjusted margin for better spacing */
}

.button-container {
  display: flex; /* Use flexbox for alignment */
  flex-direction: column; /* Stack buttons vertically */
  gap: 10px; /* Space between buttons */
}
button.el-button.el-button--primary.login-button >>> {
  width: 348px;
  background-color: #409eff; /* 设置背景颜色 */
  color: white; /* 设置字体颜色 */
  border: none; /* 去掉边框 */
  padding: 10px 20px; /* 设置内边距 */
  margin-left: 10px;
  border-radius: 5px; /* 设置圆角 */
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.register-button {
 
  padding: 10px;
  transition: background-color 0.3s;
}


.register-button {
  background-color: transparent; /* Transparent for register button */
  color: #409eff; /* Text color */
  border: 1px solid #409eff; /* Border color */
  border-radius: 4px; /* Rounded corners */
}

.register-button:hover {
  background-color: #409eff; /* Background on hover */
  color: white; /* Text color on hover */
}

.el-input .el-input__prefix {
  color: #409eff; /* Icon color */
}
</style>
